package cn.xiaolang.function.design_pattern.state;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author Dean
 * @date 2021-12-23
 */
@Slf4j
public class TrialHandler {

    /**
     * 开始审核流程
     */
    public static void start(TrialFlowContext context) {
        if (context.getNode() == null)
            context.setNode(new TrialNode());
        handle(context);
    }


    private static void handle(@NonNull TrialFlowContext context) {
        TrialNode node = context.getNode();
        String nodeName = context.getNode().getName();
        if (Boolean.TRUE.equals(context.getIsOver())) {
            log.info("[{}] trial flow is over!", context.getMessage());
            return;
        }

        if (Objects.equals(TrialStatus.PASS, node.getTrialStatus())) {
            // 初审通过，进入复审阶段
            log.info("[{}] trial pass", nodeName);
            context.setBeforeNode(node);
            TrialNode nextNode = context.getNextNode();
            if (!Objects.isNull(nextNode)) {
                context.setNode(nextNode);
                context.setNextNode(null);
            } else {
                context.setIsOver(true);
            }
        } else if (Objects.equals(TrialStatus.REJECT, node.getTrialStatus())) {
            TrialNode beforeNode = context.getBeforeNode();
            log.info("[{}] trial reject", nodeName);
            if (!Objects.isNull(beforeNode)) {
                context.setNode(beforeNode);
                node.setTrialStatus(TrialStatus.PENDING);
                context.setNextNode(node);
            }
        } else {
            log.info("[{}] trial pending", nodeName);
        }
        if (Boolean.TRUE.equals(context.getIsOver())) {
            log.info("[{}] trial flow is over!", context.getMessage());
        } else {
            log.info("[{}]: node=>{},status=>{}", context.getMessage(),
                    context.getNode().getName(), context.getNode().getTrialStatus());
        }

    }
}
